package com.power.sifa.correction.dao.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.plf.core.base.service.Ha_attachmentService;
import com.plf.core.common.dao.OffersetTransformers;
import com.power.sifa.correction.dao.Cre_workDaoCustom;
import com.power.sifa.correction.model.Cre_work;
import com.power.sifa.correction.model.pageInfo.Cre_workPageInfo;
import com.power.sifa.correction.model.pojo.vo.RecordVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.query.internal.NativeQueryImpl;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.*;

/**
 * 预警处置任务 持久层实现(hibernate)
 */

@Slf4j
@Repository
public class Cre_workDaoImpl implements Cre_workDaoCustom {

    private final EntityManager entityManager;

    @Resource
    private Ha_attachmentService ha_attachmentService;

    public Cre_workDaoImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public List queryList(Cre_workPageInfo pageInfo) {
        List<Cre_work> result = new ArrayList<>();

        StringBuffer sql = new StringBuffer("SELECT a.*, b.type, b.pername, b.rectime, b.latcamera, b.lngcamera, b.addr, b.issup, b.isrepeat, b.perid, c.crime FROM cre_work a left join cre_warning b on a.warnid = b.id left join crc_person c on b.perid = c.id" +
                " where 1 = 1 ");
        List<Object> paramsList = new ArrayList<>();
        int index = 1;
        // 处置人查询
        if (StringUtils.isNotEmpty(pageInfo.getF_userid())) {
            sql.append(" and a.userid = ?" + index++);
            paramsList.add(pageInfo.getF_userid());
        }
        // 姓名查询 app 上同一字段同时查询姓名和地点
        if (StringUtils.isNotEmpty(pageInfo.getF_pername())) {
            sql.append(" and (b.pername like ?" + index++);
            paramsList.add("%" + pageInfo.getF_pername() + "%");
            sql.append(" or b.addr like ?" + index++ + " ) ");
            paramsList.add("%" + pageInfo.getF_pername() + "%");
        }
        // 预警类型查询
        if (!CollectionUtils.isEmpty(pageInfo.getF_type())) {
            sql.append(" and b.type in ?" + index++);
            paramsList.add(pageInfo.getF_type());
        }
        // 地点查询
        if (StringUtils.isNotEmpty(pageInfo.getF_addr())) {
            sql.append(" and b.addr like ?" + index++);
            paramsList.add("%" + pageInfo.getF_addr() + "%");
        }
        // 状态
        if (!CollectionUtils.isEmpty(pageInfo.getF_status())) {
            sql.append(" and a.status in ?" + index++);
            paramsList.add(pageInfo.getF_status());
        }
        // 处置单位
        if (!CollectionUtils.isEmpty(pageInfo.getF_deptid())) {
            sql.append(" and a.deptid in ?" + index++);
            paramsList.add(pageInfo.getF_deptid());
        }
        // 是否督办
        if (StringUtils.isNotEmpty(pageInfo.getF_issup())) {
            sql.append(" and b.issup = ?" + index++);
            paramsList.add(pageInfo.getF_issup());
        }
        // 处置类型
        if (!CollectionUtils.isEmpty(pageInfo.getF_worktype())) {
            sql.append(" and a.worktype in ?" + index++);
            paramsList.add(pageInfo.getF_worktype());
        }
        // 收到时间查询
        if (ObjectUtil.isNotEmpty(pageInfo.getF_rectime())) {
            sql.append(" and b.rectime >= ?" + index++);
            paramsList.add(pageInfo.getF_rectime());
        }
        if (ObjectUtil.isNotEmpty(pageInfo.getF_rectime_01())) {
            sql.append(" and b.rectime <= ?" + index++);
            paramsList.add(pageInfo.getF_rectime_01());
        }
        // 收到时间查询
        if (ObjectUtil.isNotEmpty(pageInfo.getF_createtime())) {
            sql.append(" and a.createtime >= ?" + index++);
            paramsList.add(pageInfo.getF_createtime());
        }
        if (ObjectUtil.isNotEmpty(pageInfo.getF_createtime_01())) {
            sql.append(" and a.createtime <= ?" + index++);
            paramsList.add(pageInfo.getF_createtime_01());
        }
        // 排序
        sql.append(" order by b.rectime desc");
        Query query = entityManager.createNativeQuery(sql.toString());
        query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);
        log.info(sql.toString());

        // 添加条件
        for (int i = 0; i <= paramsList.size() - 1; i++) {
            query.setParameter(i + 1, paramsList.get(i));
        }
        // 查询总数
        pageInfo.setAllcount(query.getResultList().size());
        // 分页
        if (pageInfo.getAllcount() > 0) {
            int pageStart = (pageInfo.getPageNumber() - 1) * pageInfo.getPageSize();
            List<Map> list = query.setFirstResult(pageStart).setMaxResults(pageInfo.getPageSize()).getResultList();
            if (CollectionUtil.isNotEmpty(list)) {
                result = JSON.parseArray(JSON.toJSONString(list), Cre_work.class);
            }
        }
        return result;
    }

    @Override
    public Map<Integer, Integer> getDisposalStatus(List f_deptid) {

        StringBuffer sql = new StringBuffer("select status, count(*) from crc_person p " +
                "left join cre_warning w on p.id = w.perid " +
                "left join cre_work k on w.id = k.warnid " +
                "where 1 = 1 and status is not null");

        List<Object> paramsList = new ArrayList<>();
        int index = 1;

        if (ObjectUtil.isNotEmpty(f_deptid)) {
            sql.append(" and k.deptid in ?" + index++);
            paramsList.add(f_deptid);
        }
        sql.append(" group by k.status");

        Query query = entityManager.createNativeQuery(sql.toString());
        for (int i = 0; i <= paramsList.size() - 1; i++) {
            query.setParameter(i + 1, paramsList.get(i));
        }
        List<Object[]> resultList = query.getResultList();
        Map<Integer, Integer> statusCountMap = new HashMap<>();
        for (Object[] result : resultList) {
            Integer status = ((Number) result[0]).intValue(); // 假设状态是字符串类型
            Integer count = ((Number) result[1]).intValue(); // 假设数量是整数类型
            statusCountMap.put(status, count);
        }

        return statusCountMap;
    }

    @Override
    public List<RecordVo> findProcess(String warnId) {
        List<RecordVo> result = new ArrayList<>();

        StringBuffer sql = new StringBuffer("select r.exectime, r.fileids, w.username, w.deptname " +
                "from cre_work w " +
                "left join cre_work_record r on w.id = r.workid " +
                "where 1 = 1 ");

        List<Object> paramsList = new ArrayList<>();

        if (ObjectUtil.isNotEmpty(warnId)) {
            sql.append(" and w.warnid = ?");
            paramsList.add(warnId);
        }
        sql.append(" order by r.exectime desc");


        Query query = entityManager.createNativeQuery(sql.toString());
        query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);

        for (int i = 0; i <= paramsList.size() - 1; i++) {
            query.setParameter(i + 1, paramsList.get(i));
        }
        List<Map> list = query.getResultList();
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        for (Map map : list) {
            if (ObjectUtil.isNull(map.get("fileids"))) {
                continue;
            }
            String[] fileids = map.get("fileids").toString().split(",");
            List<String> fileUrls = new ArrayList<>();
            for (String fileid : fileids) {
                fileUrls.add(ha_attachmentService.getFileUrl(fileid));
            }
            map.remove("fileids");
            map.put("fileids", fileUrls);
        }
        result = JSON.parseArray(JSON.toJSONString(list), RecordVo.class);
        return result;
    }
}
